package util;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 在线人数统计
 */

@WebListener
public class OnlineListener implements HttpSessionListener {

    private Integer onlineNum = -1;

    public Integer getOnlineNum() {
        return onlineNum;
    }

    public void setOnlineNum(Integer onlineNum) {
        this.onlineNum = onlineNum;
    }

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        onlineNum++;

        httpSessionEvent.getSession().getServletContext().setAttribute("onlineNum", onlineNum);
        System.out.println("创建新的"+onlineNum);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        onlineNum = onlineNum-2;

        httpSessionEvent.getSession().getServletContext().setAttribute("onlineNum", onlineNum);
        System.out.println("旧的"+onlineNum);
    }
}
